<script lang="ts" setup>
import { ref, computed, watch, inject } from 'vue';
import { Menu } from '@ark-ui/vue/menu';
import { Switch } from '@ark-ui/vue/switch';
import { useMouseInElement, useElementHover } from '@vueuse/core';
import { $fetch } from '@/settings/utils/fetch';
import { gotoLoginForClient, gotoLogoutForClient } from '@/common/utils/auth';
import { setLanguageFromClient } from '@/common/utils/language';
import { useI18n } from 'vue-i18n';
import { useAppStore, useUserStore } from '@/settings/stores';

import NavigationBar from '@/common/components/navigation-bar/index.vue';

defineOptions({
  name: 'OpenNavBar',
});

const atomgitUrl = import.meta.env.VITE_ATOMGIT_URL;

const menubarEl = ref(null);
const newMenuEl = ref(null);
const userMenuEl = ref(null);
const isForceMenubarClose = ref(false);
const menubarItems = ref<Record<string, any>[]>([]);
const unreadCount = ref<Record<string, number>>({});

const appStore = useAppStore();
const userStore = useUserStore();
const { isOutside: isMenubarOutside } = useMouseInElement(menubarEl);
const isNewMenuHovered = useElementHover(newMenuEl, { delayEnter: 200, delayLeave: 200 });
const isUserMenuHovered = useElementHover(userMenuEl, { delayEnter: 200, delayLeave: 200 });
const { locale } = useI18n();

const getMenubar = async () => {
  const { isSuccess, data } = await $fetch('/toolbar/queryToolbarListByCommunityId');

  if (isSuccess) {
    menubarItems.value = data;
  }
}

getMenubar();

const getUnreadCount = async () => {
  const { isSuccess, data } = await $fetch('/user/unreadCount');

  if (isSuccess) {
    unreadCount.value = data;
  }
}

getUnreadCount();

const isUnread = computed(() => Object.values(unreadCount.value ?? {}).reduce((x: number, y: number) => x + y, 0) > 0);

watch(isMenubarOutside, () => {
  isForceMenubarClose.value = false;
});

const login = () => {
  gotoLoginForClient();
}

const logout = () => {
  gotoLogoutForClient();
}

const languageValue = ref(locale.value === 'zh-CN');

const changeLanguage = ({ checked }: { checked: boolean }) => {
  setLanguageFromClient(checked ? 'zh-CN' : 'en-US');
  window.location.reload();
}

const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;
</script>

<template>
  <header class="open-nav-bar relative z-9999 h-64 bg-white text-14 color-text-2 2xl:text-16">
    <div class="mx-20 h-full flex-y-center justify-between">
      <div class="h-44 w-140 flex-shrink-0">
        <a href="/" class="block size-full">
          <img :src="appStore.config.logo" :alt="appStore.config.name" class="block size-full object-contain object-left">
        </a>
      </div>

      <div class="ml-20" v-if="appStore.device === 'mobile'">
        <IconMenuFold class="cursor-pointer text-22px" @click="toggleDrawerMenu" />
      </div>

      <div class="mx-60 h-full">
        <NavigationBar :menubar-items="menubarItems" />
      </div>

      <div class="flex-y-center flex-shrink-0">
        <div class="flex-y-center gap-x-20 text-14" v-if="userStore.user.id">
          <a :href="`${atomgitUrl}/-/profile/notice/message`" target="_blank" class="relative block h-20 w-20" :aria-label="$t('common.header.notice.tooltip')">
            <div class="i-icons:notification h-full w-full"></div>
            <div class="absolute right--3 top--3 h-6 w-6 rounded-50% bg-hex-E24E40" v-if="isUnread"></div>
          </a>

          <div ref="newMenuEl">
            <Menu.Root id="page-header-menu-new" :open="isNewMenuHovered" lazy-mount close-on-select :positioning="{ placement: 'bottom-end', gutter: 0 }">
              <Menu.Trigger as-child>
                <a :href="`${atomgitUrl}/-/profile/community/article`" target="_blank" class="flex-x-center gap-x-2 rounded-4 bg-primary-1 px-12 py-6 color-white leading-20 focus-visible:outline-unset">
                  <div class="i-icons:plus-1 h-20 w-20"></div>
                  {{ $t('common.header.new.menu1') }}
                </a>
              </Menu.Trigger>
              <Menu.Positioner>
                <div class="flex">
                  <div>
                    <Menu.Content as-child>
                      <div class="mt-12 overflow-hidden rounded-6 bg-white p-8 shadow-[0_5px_15px_0_rgba(0,0,0,0.15)] focus-visible:outline-unset">
                        <Menu.Item as-child value="article">
                          <a :href="`${atomgitUrl}/-/editor/drafts/new`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2) focus-visible:(outline-unset)">
                            {{ $t('common.header.new.menu5') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="repository">
                          <a :href="`${atomgitUrl}/-/profile/community/repository`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2) focus-visible:(outline-unset)">
                            {{ $t('common.header.new.menu2') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="organization">
                          <a :href="`${atomgitUrl}/-/profile/community/organization`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.new.menu4') }}
                          </a>
                        </Menu.Item>
                      </div>
                    </Menu.Content>
                  </div>
                </div>
              </Menu.Positioner>
            </Menu.Root>
          </div>

          <div ref="userMenuEl">
            <Menu.Root id="page-header-menu-user" :open="isUserMenuHovered" lazy-mount close-on-select :positioning="{ placement: 'bottom-end', gutter: 0 }">
              <Menu.Trigger as-child>
                <div class="h-24 w-24 focus-visible:outline-unset">
                  <img :src="userStore.user.photo" class="block h-full w-full rounded-50% object-cover">
                </div>
              </Menu.Trigger>
              <Menu.Positioner>
                <div class="flex">
                  <div>
                    <Menu.Content as-child>
                      <div class="mt-17 overflow-hidden rounded-6 bg-white p-8 shadow-[0_5px_15px_0_rgba(0,0,0,0.15)] focus-visible:outline-unset">
                        <Menu.Item as-child value="user-info" :close-on-select="false">
                          <div class="px-20 pb-4">
                            <p class="font-medium leading-20">{{ userStore.user.nickname }}</p>
                            <p class="text-12 leading-20">@{{ userStore.user.username }}</p>
                          </div>
                        </Menu.Item>
                        <Menu.Separator class="my-8 b-color-gray-2" />
                        <Menu.Item as-child value="language" :close-on-select="false">
                          <div class="h-44 flex-y-center gap-x-6 px-20 data-[highlighted]:(rounded-4 bg-gray-2)">
                            <div>{{ $t('common.languageName', '', { locale: 'zh-CN' }) }}</div>
                            <Switch.Root v-model:checked="languageValue" id="page-header-switch-language" class="mt-2 block" @checked-change="changeLanguage">
                              <Switch.Control class="flex-shark-0 block h-16 w-28 flex-y-center cursor-pointer rounded-full bg-gray-3 p-2 transition-background-color data-[state=checked]:(bg-primary-2)">
                                <Switch.Thumb class="block h-12 w-12 translate-x-100% rounded-full bg-white transition-transform data-[state=checked]:(translate-x-0)" />
                              </Switch.Control>
                              <Switch.HiddenInput />
                            </Switch.Root>
                            <div>{{ $t('common.languageName', '', { locale: 'en-US' }) }}</div>
                          </div>
                        </Menu.Item>
                        <Menu.Item as-child value="my-homepage">
                          <a :href="`${atomgitUrl}/${userStore.user.username}`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2) focus-visible:(outline-unset)">
                            {{ $t('common.header.user.menu1') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="my-repository">
                          <a :href="`${atomgitUrl}/users/${userStore.user.username}/projects`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.user.menu2') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="my-organization">
                          <a :href="`${atomgitUrl}/-/profile/orgs`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.user.menu3') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="my-changes">
                          <a :href="`${atomgitUrl}/dashboard/changes`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.user.menu4') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="my-issues">
                          <a :href="`${atomgitUrl}/dashboard/issues`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.user.menu5') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="my-starred">
                          <a :href="`${atomgitUrl}/users/${userStore.user.username}/starred`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.user.menu6') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="my-profile">
                          <a :href="`${atomgitUrl}/-/profile`" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.user.menu7') }}
                          </a>
                        </Menu.Item>
                        <Menu.Separator class="my-8 b-color-gray-2" />
                        <Menu.Item as-child value="help">
                          <a href="https://docs.atomgit.com/" target="_blank" class="block px-20 leading-44 data-[highlighted]:(rounded-4 bg-gray-2)">
                            {{ $t('common.header.user.menu9') }}
                          </a>
                        </Menu.Item>
                        <Menu.Item as-child value="logout">
                          <button type="button" class="block h-44 w-full bg-transparent px-20 text-left data-[highlighted]:(rounded-4 bg-gray-2)" @click="logout">
                            {{ $t('common.header.user.menu10') }}
                          </button>
                        </Menu.Item>
                      </div>
                    </Menu.Content>
                  </div>
                </div>
              </Menu.Positioner>
            </Menu.Root>
          </div>
        </div>

        <div class="flex gap-x-16 text-14" v-else>
          <button type="button" class="bg-transparent px-12 py-6 hover:(color-primary-2)" @click="login">{{ $t('common.header.register') }}</button>
          <button type="button" class="rounded-4 bg-primary-1 px-12 py-6 color-white" @click="login">{{ $t('common.header.login') }}</button>
        </div>
      </div>
    </div>
  </header>
</template>

<style lang="scss" scoped>
.open-nav-bar {
  [data-scope=menu][data-part=content][hidden] {
    display: none;
  }

  [data-scope=menu][data-part=content][data-state=open] {
    animation: fadeIn 0.15s ease-out;
  }

  [data-scope=menu][data-part=content][data-state=closed] {
    animation: fadeOut 0.1s ease-out;
  }

  @keyframes fadeIn {
    from {
      max-height: 0;
      opacity: 0;
    }

    to {
      max-height: 100%;
      opacity: 1;
    }
  }

  @keyframes fadeOut {
    from {
      max-height: 100%;
      opacity: 1;
    }

    to {
      max-height: 0;
      opacity: 0;
    }
  }
}
</style>
